package com.andreas.controller.management;

import com.andreas.exception.BussinessException;
import com.andreas.pojo.Book;
import com.andreas.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author andreaszhou
 * @ClassName MBookController
 * @Description TODO
 * @date 2021/1/22 14:37
 * @Version 1.0
 */
@Controller
@RequestMapping("/management")
public class MBookController {
    @Resource
    private BookService bookServiceImp;


    /*
    * 显示后台管理首页
    * */
    @GetMapping("index")
    public ModelAndView showManageIndex(){
        ModelAndView modelAndView = new ModelAndView("/management/index");
        return modelAndView;
    }

    /*
    * 显示后台管理--图书管理
    *
    * */
    @GetMapping("/book")
    public ModelAndView showManageBook(){
        ModelAndView modelAndView = new ModelAndView("management/book");
        return modelAndView;
    }
    @GetMapping("/book/list")
    @ResponseBody
    public Map list(Integer page,Integer limit){
        IPage<Book> iPage = bookServiceImp.showBookService(null, null, page, limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","success");
        map.put("data",iPage.getRecords());
        map.put("count",iPage.getTotal());
        return map;
    }

    /*
    *
    * 显示后台管理--短评管理
    * */
    @GetMapping("/evaluation")
    public ModelAndView showManageEvaluation(){
        ModelAndView modelAndView = new ModelAndView("/management/evaluation");
        return modelAndView;
    }

    @PostMapping("/book/create")
    @ResponseBody
    public Map createBook(Book book){
        Map map = new ManagedMap();
        try{
            book.setEvaluationQuantity(0);
            book.setEvaluationScore(0);
            Document document = Jsoup.parse(book.getDescription());
            Element img = document.select("img").first();
            String cover = img.attr("src");
            book.setCover(cover);
            bookServiceImp.createBook(book);
            map.put("code","0");
            map.put("msg","success");
        }catch (BussinessException e){
            e.printStackTrace();
            map.put("code",e.getCode());
            map.put("msg",e.getMsg());
        }
        return map;
    }

}
